package com.louis.ylog.advice;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.util.StringUtils;
import com.louis.ylog.TraceContext;
import com.louis.ylog.feign.CatConstantsExt;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 各项目自定义的aop切面
 */
@Slf4j
public class CustomerCatAdvice  implements MethodInterceptor {

    private String catTitle= CatConstantsExt.Type_Spring_Bean_Method;

    public CustomerCatAdvice(){
    }

    public CustomerCatAdvice(String catTitle){
        if(!StringUtils.isEmpty(catTitle)){
            this.catTitle=catTitle;
        }
    }

    private String getMethodString(MethodInvocation invocation){
        try {
            return String.format("%s.%s(%s)",invocation.getMethod().getDeclaringClass().getName(),invocation.getMethod().getName(), Arrays.stream(invocation.getMethod().getGenericParameterTypes()).map(s->".").collect(Collectors.joining("")));
        }catch (Exception ex){
            log.error("获取方法签名异常",ex);
            return "N/A";
        }
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Transaction t = null;
        try {
            if(TraceContext.isCatEnable()){
                t = Cat.newTransaction(catTitle,getMethodString(invocation));
            }
            //调用 proceed() 方法才会真正的执行实际被代理的方法
            Object result = invocation.proceed();
            if(null!=t){
                t.setStatus(Message.SUCCESS);
            }
            return result;
        } catch (Throwable te) {
            if(null!=t){
                t.setStatus(te);
            }
            throw te;
        }finally {
            if(null!=t){
                t.complete();
            }
        }
    }
}
